import React, { useState, useEffect } from 'react'
import { connect } from 'dva'
import { Col, Form, Input, Button, Card, Select, Table, DatePicker } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { fetchFlqsInfo, fetchPosList, fetchStoresList, exportExcel, fetchRateList, exportPDF } from '@/services/dataCenter/financeData'
import { formLayout } from '@/utils/utils'
import SearchBox from '@/components/SearchBox'
import RenderButtom from '@/components/RenderButton'
import moment from 'moment'
const {RangePicker} = DatePicker

const RateSettle = props => {
  const { form, payTypes, platForms } = props
  const { getFieldDecorator } = form
  const [posList, setPosList] = useState([])
  const [storesList, setStoresList] = useState([])
  const [dateFormat, setDateFormat] = useState('YYYY-MM-DD')
  const [total, setTotalPage] = useState(null)
  const [rateList, setRateList] = useState([])
  const [param, setParam] = useState({pageNo: 1, pageSize: 10,})
  const [pageInfo, setPageInfo] = useState({pageTotalMoney: 0, pageRateAmount: 0, pageArrivalAmount: 0})
  const [totalInfo, setTotalInfo] = useState({totalMoney: 0, totalRateAmout: 0, arrivalAmount: 0})

  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 97:
        form.validateFields(async (err, values) => {
          console.log(values)
          exportExcel(values).then(() => {
            console.log(res)
          })
        })
        break;
      default:
        break;
    }
  }
  useEffect(() => {
    _fetchStoresList()
    _fetchPosList()
    _fetchFlqsInfo()
    init()
  }, [])
  const _fetchStoresList = async () => {
    let param = {
      // supplierId: form.getFieldValue('supplierId'),
      supplierId: 1072,
      pageSize: 999
    }
    const res = await fetchStoresList(param)
    setStoresList(res.data)
  }
  const _fetchPosList = async () => {
    const res = await fetchPosList()
    setPosList(res.data)
  }
  const _fetchFlqsInfo = async () => {
    const res = await fetchFlqsInfo()
    setTotalInfo({
      totalMoney: res.data.totalMoney,
      totalRateAmout: res.data.totalRateAmout,
      arrivalAmount: Number(res.data.totalMoney) - Number(res.data.totalRateAmout)
    })
  }
  const init = async (param) => {
    const res = await fetchRateList({param})
    setRateList(res.data)
    setTotalPage(res.total)
    setPageInfo({
      pageTotalMoney: res.pageTotalMoney,
      pageRateAmount: res.pageRateAmount,
      pageArrivalAmount: res.pageAccountMoney
    })
  }
  const pagination = {
    total: parseInt(total),
    onChange (page) {
      init({
        ...param,
        pageNo: page,
      })
    }
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log(values)
      init({
        ...param,
        startTime: values.selectedTime ? values.selectedTime[0].format(dateFormat) : null,
        endTime: values.selectedTime ? values.selectedTime[1].format(dateFormat) : null,
      })
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (v, r, i) => {
        return (<span>{i+1}</span>)
      }
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      key: 'storeName',
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
    {
      title: '支付订单号',
      dataIndex: 'payOrderNo',
      key: 'payOrderNo',
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
    },
    {
      title: '支付类型',
      dataIndex: 'payTypeName',
      key: 'payTypeName',
    },
    {
      title: '支付金额',
      dataIndex: 'payAmount',
      key: 'payAmount',
    },
    {
      title: '扣费金额',
      dataIndex: 'rateAmount',
      key: 'rateAmount',
    },
    {
      title: '到账金额',
      dataIndex: 'accountAmount',
      key: 'accountAmount',
    },
    {
      title: '订单来源',
      dataIndex: 'paySourceName',
      key: 'paySourceName',
    },
    {
      title: '银行卡号',
      dataIndex: 'cardNo',
      key: 'cardNo',
    },
    {
      title: '卡类型',
      dataIndex: 'accountTypeName',
      key: 'accountTypeName',
    },
    {
      title: '所属银行',
      dataIndex: 'cardlssuerCode',
      key: 'cardlssuerCode',
    },
  ]

  // 查询条件
  const getFields = () => {
    return(<>
      <Col span={8}>
        <Form.Item label="门店" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('storeId', { initialValue: '2063',})
            (<Select></Select>)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="pos机" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('posSn', {})
            (<Select>
              {posList.map((m, i) => <Select.Option key={i} value={m.sn}>{m.posName}</Select.Option>)}
            </Select>
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="订单号" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('orderNo', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="支付订单号" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('payOrderNo', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="支付类型" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('payTypes', {})
            (<Select mode="multiple">
              {payTypes.map((m, i) => <Select.Option key={i} value={m.value}>{m.label}</Select.Option>)}
            </Select>
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`付款时间`} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator(`selectedTime`, {
            defaultValue: [moment(), moment()],
          })
            (<RangePicker format={dateFormat} />)}
        </Form.Item>
      </Col>
    </>)
  }
  return (<PageHeaderWrapper>
    <Card>
      <Form layout={formLayout}>
        <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      </Form>
    </Card>
    <Card style={{marginTop: '10px'}} title="根据pos机设置费率，计算出每一笔订单的扣费记录">
      <RenderButtom click={handleBtn} />
      <Table rowKey={record => record.id} pagination={pagination} size="small" columns={columns} dataSource={rateList}/>
      <p>总 计：实付：¥{totalInfo.totalMoney} 扣费：¥{totalInfo.totalRateAmout} 到账金额：¥{totalInfo.arrivalAmount}</p>
      <p>页小计：实付：¥{pageInfo.pageTotalMoney} 扣费: ¥{pageInfo.pageRateAmount} 到账金额：¥{pageInfo.pageArrivalAmount}</p>
    </Card>
  </PageHeaderWrapper>)
}

export default connect(({global}) => ({
  platForms: global.platForms,
  payTypes: global.payTypes
}))(Form.create()(RateSettle))
